<template>
  <div>
    <canvas id="oriCanvas"></canvas>
    <canvas id="dstCanvas"></canvas>
    <el-row>
      <el-radio v-model="radio" label="1">画笔</el-radio>
      <el-radio v-model="radio" label="2">橡皮擦</el-radio>
    </el-row>
  </div>
</template>
<script>
export default {
  name: 'testB',
  data () {
    return {
      radio: '1',
      img: 'http://img3.imgtn.bdimg.com/it/u=3543954389,1979127086&fm=26&gp=0.jpg'
    }
  },
  mounted () {
    var oriCanvas = document.getElementById("oriCanvas");
    var dstCanvas = document.getElementById("dstCanvas");
    var dstCtx = dstCanvas.getContext("2d");
    var oriCtx = oriCanvas.getContext("2d");
    var image = new Image();
    image.src = this.img
    var _that = this
    image.onload = function () {
      dstCanvas.width = this.width;
      dstCanvas.height = this.height;
      dstCtx.drawImage(this, 0, 0);
      oriCanvas.width = this.width;
      oriCanvas.height = this.height;
      oriCtx.drawImage(this, 0, 0);
    }
    // --------- 画笔和橡皮擦功能实现 -------------
    var flag = false;  // 记录鼠标按下和抬起时间  标记画笔是否开始工作
    var isXp = _that.radio === '2'; // 记录画笔是橡皮还是画笔
    var lineWidth = 50; // 设置画笔粗细
    // // 设置画笔颜色
    // var theColor = document.getElementById("color");
    // theColor.onchange = function () {
    //   dstCtx.strokeStyle = this.value;
    // }
    dstCanvas.onmousedown = function (eva) {
      var eva = eva || window.event;
      dstCtx.lineCap = "round";
      dstCtx.lineJoin = "round";
      var x = eva.offsetX;
      var y = eva.offsetY;
      dstCtx.beginPath();
      dstCtx.moveTo(x, y);
      flag = true;

      dstCtx.lineWidth = lineWidth;
      // dstCtx.strokeStyle = document.getElementById("color").value;
    }
    dstCanvas.onmousemove = function (eva) {
      if (flag) {
        if (_that.radio === '2') {
          var w = lineWidth;
          let pxs = oriCtx.getImageData(eva.offsetX - w / 2, eva.offsetY - w / 2, w, w);
          dstCtx.putImageData(pxs, eva.offsetX - w / 2, eva.offsetY - w / 2);
        }
        else {
          var eva = eva || window.event;
          var x = eva.offsetX;
          var y = eva.offsetY;
          dstCtx.lineTo(x, y);
          dstCtx.stroke();
        }
      }
    }
    dstCanvas.onmouseup = function () {
      flag = false;
      dstCtx.closePath();
    }
    dstCanvas.onmouseleave = function () {
      flag = false;
      dstCtx.closePath();
    }
  }
}
</script>
<style scoped>
#oriCanvas {
  display: none;
}
</style>